<?php

namespace app\admin\controller;

use think\Db;

class Gg extends Authorized
{

    public function index()
    {
        return $this->fetch();
    }


    public function getList()
    {
        $get_data=$this->request->get();
        $post_data = $this->request->post();

        $page = $get_data['page'];
        $limit = $get_data['limit'];

        $keywords = input('keywords');
        $where=[];

        if (!empty($keywords)){
            $where['name']=['like','%'.$keywords.'%'];
        }



        $count=Db::table('tb_news')
            ->where($where)->count();
        $rows=Db::table('tb_news')
            ->where($where)
            ->order('sort desc,id desc')
            ->page($page, $limit)
            ->select();
        return json(['code' =>0,'msg' =>'success','count' =>$count,'data'=>$rows]);
    }

    public function add()
    {
        $post_data = $this->request->post();
        if($post_data){
            $post_data['intime'] =date('Y-m-d H:i:s',time());

            Db::table('tb_news')->startTrans();
            $id =Db::table('tb_news')->insertGetId($post_data);
            if (false === $id) {
                Db::table('tb_news')->rollback();
                return json(['code' =>1,'count' =>0,'msg' =>'添加失败','data'=>'']);
            } else {
               Db::table('tb_news')->commit();
                return json(['code' =>0,'count' =>0,'msg' =>'添加成功','data'=>'']);
            }
        }

        $article=Db::table('tb_news')->order('sort desc,id desc')->select();
        $this->assign('article', $article);
       return $this->fetch();
    }

    public function edit()
    {
        $post_data = $this->request->post();
        if($post_data){


            $result =Db::table('tb_news')->where('id', $post_data['id'])->setField(['name'=>$post_data['name'],'content'=>$post_data['content']]);

            if (false === $result) {
                return json(['msg' =>'失败', 'code' =>1,'data'=>Db::table('tb_news')->getLastSql()]);
            } else {
                return json(['msg' =>'成功', 'code' =>0,]);
            }
        }

        $article=Db::table('tb_news')
            ->where('id' , input('id'))
            ->find();
        $this->assign('article', $article);
        return $this->fetch();
    }

    public function show()
    {
        $article=Db::table('tb_news')->where('id' , input('id'))->find();
        $this->assign('article', $article);
        return $this->fetch();
    }


    public function del()
    {
        $data = $this->request->post();
        if($data){
            $result =Db::table('tb_news')->where('id', $data['id'])->delete();
            if (false === $result) {
                return json(['msg' =>'删除失败', 'code' =>1]);
            } else {
                return json(['msg' =>'删除成功', 'code' =>0]);
            }
        }
    }
}